// 创建分享页面逻辑
const app = getApp();

Page({
  data: {
    // 表单数据
    formData: {
      title: '',
      content: '',
      images: [],
      tags: '',
      type: 'experience'
    },
    
    // 分享类型选项
    typeOptions: [
      { name: '经验分享', value: 'experience' },
      { name: '问题求助', value: 'question' },
      { name: '成果展示', value: 'achievement' },
      { name: '知识科普', value: 'knowledge' }
    ],
    typeIndex: 0,
    
    // 提交状态
    submitting: false,
    canSubmit: false
  },

  // 统一图片 URL 构造（供本页预览使用）
  getImageUrl(imagePath) {
    const { buildMediaUrl } = require('../../../utils/media');
    return buildMediaUrl(imagePath);
  },

  onLoad() {
    console.log('创建分享页面加载');
  },

  // 检查表单是否可以提交
  checkCanSubmit() {
    const { title, content } = this.data.formData;
    const canSubmit = title.trim() && content.trim();
    this.setData({ canSubmit });
  },

  // 分享类型选择
  onTypeChange(e) {
    const typeIndex = parseInt(e.detail.value);
    const type = this.data.typeOptions[typeIndex].value;
    
    this.setData({
      typeIndex,
      'formData.type': type
    });
  },

  // 标题输入
  onTitleInput(e) {
    this.setData({
      'formData.title': e.detail.value
    });
    this.checkCanSubmit();
  },

  // 内容输入
  onContentInput(e) {
    this.setData({
      'formData.content': e.detail.value
    });
    this.checkCanSubmit();
  },

  // 标签输入
  onTagsInput(e) {
    this.setData({
      'formData.tags': e.detail.value
    });
  },

  // 选择图片
  async onChooseImage() {
    try {
      const res = await wx.chooseMedia({
        count: 4 - this.data.formData.images.length,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed']
      });

      const newImages = res.tempFiles.map(file => file.tempFilePath);
      const currentImages = this.data.formData.images;
      
      this.setData({
        'formData.images': [...currentImages, ...newImages]
      });
    } catch (error) {
      console.error('选择图片失败:', error);
      if (error.errMsg !== 'chooseMedia:fail cancel') {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    }
  },

  // 删除图片
  onDeleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.formData.images];
    images.splice(index, 1);
    
    this.setData({
      'formData.images': images
    });
  },

  // 上传图片到服务器
  async uploadImages(images) {
    return Promise.all(images.map((imagePath, index) => new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${app.globalData.apiBaseUrl}/upload/image?category=social`,
        filePath: imagePath,
        name: 'image',
        formData: { category: 'social' },
        header: { 'Authorization': `Bearer ${app.globalData.token}` },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.success) resolve(data.data.url);
            else reject(new Error(data.message || '上传失败'));
          } catch (e) { reject(new Error('上传响应解析失败')); }
        },
        fail: (err) => reject(new Error(err.errMsg || '上传失败'))
      });
    })));
  },

  // 提交表单
  async onSubmit(e) {
    if (!this.data.canSubmit || this.data.submitting) {
      return;
    }

    this.setData({ submitting: true });

    try {
      const { title, content, images, tags, type } = this.data.formData;
      
      console.log('开始提交分享:', { title, content, images: images.length, tags, type });
      console.log('使用的apiBaseUrl:', app.globalData.apiBaseUrl);
      console.log('使用的token:', app.globalData.token ? '有token' : '无token');
      
      // 先测试基本的网络连接
      try {
        console.log('测试基本网络连接...');
        const testRes = await new Promise((resolve, reject) => {
          wx.request({
            url: `${app.globalData.apiBaseUrl}/social/get-shares`,
            method: 'GET',
            header: {
              'Authorization': `Bearer ${app.globalData.token}`
            },
            success: resolve,
            fail: reject
          });
        });
        console.log('基本网络连接测试成功:', testRes.statusCode);
      } catch (testError) {
        console.error('基本网络连接测试失败:', testError);
        throw new Error('网络连接失败，请检查服务器状态');
      }
      
      // 上传图片
      let imageUrls = [];
      if (images.length > 0) {
        wx.showLoading({ title: '上传图片中...' });
        console.log('开始上传', images.length, '张图片');
        imageUrls = await this.uploadImages(images);
        console.log('图片上传完成:', imageUrls);
      }

      wx.showLoading({ title: '发布中...' });

      // 创建分享
      const res = await new Promise((resolve, reject) => {
        const requestData = {
          title: title.trim(),
          content: content.trim(),
          images: imageUrls,
          tags: tags.trim() || '',
          share_type: type
        };
        
        console.log('发送创建分享请求:', requestData);
        console.log('请求URL:', `${app.globalData.apiBaseUrl}/social/create-share`);
        console.log('请求headers:', {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${app.globalData.token.substring(0, 20)}...`
        });
        
        wx.request({
          url: `${app.globalData.apiBaseUrl}/social/create-share`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: requestData,
          timeout: 10000, // 10秒超时
          success: (res) => {
            console.log('创建分享成功响应:', res);
            resolve(res);
          },
          fail: (error) => {
            console.error('创建分享请求失败:', error);
            console.error('错误详情:', JSON.stringify(error));
            reject(error);
          }
        });
      });

      wx.hideLoading();

      if (res.statusCode === 201) {
        const data = res.data;
        if (data.success) {
          wx.showToast({
            title: '发布成功',
            icon: 'success'
          });
          
          // 返回社区页面并刷新
          setTimeout(() => {
            wx.navigateBack({
              success: () => {
                // 通知社区页面刷新数据
                const pages = getCurrentPages();
                const prevPage = pages[pages.length - 2];
                if (prevPage && prevPage.refreshData) {
                  prevPage.refreshData();
                }
              }
            });
          }, 1500);
        } else {
          throw new Error(data.message || '发布失败');
        }
      } else {
        throw new Error('网络请求失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('发布失败:', error);
      wx.showToast({
        title: error.message || '发布失败',
        icon: 'none'
      });
    } finally {
      this.setData({ submitting: false });
    }
  }
});
